package com.maoye.ossp.biz.contract.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.beust.jcommander.internal.Maps;
import com.google.common.collect.Lists;
import com.hotent.base.api.query.QueryFilter;
import com.hotent.base.api.query.QueryOP;
import com.hotent.base.core.util.string.StringUtil;
import com.maoye.ossp.biz.brand.entity.BrandPositionLog;
import com.maoye.ossp.biz.brand.service.BrandPositionLogService;
import com.maoye.ossp.biz.brand.utils.BrandCommonConstant;
import com.maoye.ossp.biz.contract.entity.AdvertAssociated;
import com.maoye.ossp.biz.contract.entity.AssociatedContract;
import com.maoye.ossp.biz.contract.entity.LeaseAssociated;
import com.maoye.ossp.biz.contract.entity.MarketAssociated;
import com.maoye.ossp.biz.contract.entity.SelfAssociated;
import com.maoye.ossp.biz.contract.service.IAdvertAssociatedService;
import com.maoye.ossp.biz.contract.service.IContractService;
import com.maoye.ossp.biz.contract.service.ILeaseAssContractService;
import com.maoye.ossp.biz.contract.service.IMarketAssociatedService;
import com.maoye.ossp.biz.contract.service.ISelfAssociatedService;
import com.maoye.ossp.biz.contract.utils.ContractUtils;
import com.maoye.ossp.biz.negotiation.entity.Assinfo;
import com.maoye.ossp.biz.negotiation.entity.Assrecords;
import com.maoye.ossp.biz.negotiation.entity.NegAssTempItemCode;
import com.maoye.ossp.biz.negotiation.entity.NegAssbaseitems;
import com.maoye.ossp.biz.negotiation.entity.NegAssbrands;
import com.maoye.ossp.biz.negotiation.entity.NegAssitems;
import com.maoye.ossp.biz.negotiation.entity.NegAssshops;
import com.maoye.ossp.biz.negotiation.entity.NegStore;
import com.maoye.ossp.biz.negotiation.service.AssinfoService;
import com.maoye.ossp.biz.negotiation.service.AssrecordService;
import com.maoye.ossp.biz.negotiation.service.NegAssbaseitemsService;
import com.maoye.ossp.biz.negotiation.service.NegAssbrandsService;
import com.maoye.ossp.biz.negotiation.service.NegAssbshService;
import com.maoye.ossp.biz.negotiation.service.NegAssitemsService;
import com.maoye.ossp.biz.negotiation.service.NegAssshopsService;
import com.maoye.ossp.biz.negotiation.util.BuildEntity;
import com.maoye.ossp.common.entity.Page;
import com.maoye.ossp.common.web.BaseController;
import com.maoye.ossp.sys.base.entity.BerthMaindata;
import com.maoye.ossp.sys.base.entity.CMCate;
import com.maoye.ossp.sys.base.entity.ContractArticle;
import com.maoye.ossp.sys.base.entity.ContractArticleType;
import com.maoye.ossp.sys.base.entity.ContractRateCode;
import com.maoye.ossp.sys.base.service.BerthMaindataService;
import com.maoye.ossp.sys.base.service.ContractArticleService;
import com.maoye.ossp.sys.base.service.ContractArticleTypeService;
import com.maoye.ossp.sys.base.service.ContractRateCodeService;
import com.maoye.ossp.sys.base.service.ICMCateService;
import com.maoye.ossp.sys.msg.entity.Message;
import com.maoye.ossp.sys.msg.entity.TodoMessage;
import com.maoye.ossp.sys.msg.handler.MsgStrategyContext;
import com.maoye.ossp.sys.msg.util.MessageConstant;
import com.maoye.ossp.sys.org.util.UserUtils;
import com.maoye.sc.api.domain.User;
import com.maoye.sc.service.user.UserServiceImpl;

/**
 * 联营意向洽谈
 * 
 * @author LIUWEI
 * @data 2014年2月25日
 */
@Controller()
@RequestMapping(value = "biz/contract/assrecord")
public class AssrecordController extends BaseController {

	@Resource
	AssrecordService assrecordService;
	@Resource
	AssinfoService assinfoService;
	@Resource
	NegAssbrandsService negAssbrandsService;
	@Resource
	NegAssshopsService negAssshopsService;
	@Resource
	NegAssbshService negAssbshService;
	@Resource
	NegAssbaseitemsService negAssbaseitemsService;
	@Resource
	NegAssitemsService negAssitemsService;
	@Resource
	private ICMCateService icmCateService;		//招商分类
	@Resource
	BrandPositionLogService brandPositionLogService;	//招商信息
	@Resource
	BerthMaindataService berthMaindataService;		//铺位信息
	@Resource
	private IContractService contractServce;		//联营合同
	@Resource
	private ISelfAssociatedService selfService;		//自营合同
	@Resource
	private IMarketAssociatedService marketService;	 //促销合同
	@Resource
	private UserServiceImpl  userServiceImpl;
	@Resource
	private ILeaseAssContractService leaseService;
	@Resource
	private IAdvertAssociatedService advertService;
	@Resource
	MsgStrategyContext mscServicec;
	@Resource
	ContractArticleTypeService contractArticleTypeService;
	@Resource
	ContractArticleService contractArticleService;
	@Resource
	ContractRateCodeService contractRateCodeService;
	@Resource
	IContractService contractService;
	@Resource
	ISelfAssociatedService selfAssociatedService;
	@Resource
	IAdvertAssociatedService advertAssociatedService;
	@Resource
	ILeaseAssContractService leaseAssContractService;
	@Resource
	IMarketAssociatedService marketAssociatedService;
	@Resource
	ContractArticleService articleService;
	
	/**
	 * 显示列表
	 * @author LIUWEI
	 */
	@RequestMapping(value="getList")	
	public String getList(Assrecords assrecords, HttpServletRequest request, Model model){
		QueryFilter queryFilter = getQuerFilter(request,assrecords);
		Assinfo assinfo = assrecords.getAssinfo();
		User user=userServiceImpl.getUserById(UserUtils.getCurrentUserId().toString());
		if(assinfo !=null){
			queryFilter.addFilter("area", assinfo.getArea(), QueryOP.EQUAL);
			queryFilter.addFilter("areaId",  assinfo.getAreaId(), QueryOP.EQUAL);
			queryFilter.addFilter("store", assinfo.getStore(), QueryOP.EQUAL);
			queryFilter.addFilter("storeId",  assinfo.getStoreId(), QueryOP.EQUAL);
			queryFilter.addFilter("floor", assinfo.getFloor(), QueryOP.EQUAL);
			queryFilter.addFilter("floorId",  assinfo.getFloorId(), QueryOP.EQUAL);
			queryFilter.addFilter("status", assinfo.getStatus(), QueryOP.EQUAL);
			queryFilter.addFilter("negotiationType", assinfo.getNegotiationType(), QueryOP.EQUAL);
			queryFilter.addFilter("number", assinfo.getNumber(), QueryOP.EQUAL);
			queryFilter.addFilter("contractType", assinfo.getContractType(), QueryOP.EQUAL);
			queryFilter.addFilter("contractNo", assinfo.getContractNo(), QueryOP.EQUAL);
			String isModifyContract = assinfo.getIsModifyContract();
			if(ContractUtils.NEG_ISMODIFYCONTRACT_N.equals(isModifyContract)){
				isModifyContract = "";
			}
			queryFilter.addFilter("isModifyContract", isModifyContract, QueryOP.EQUAL);
			queryFilter.addFilter("negotiationType", assinfo.getNegotiationType(), QueryOP.EQUAL);
		}
		if(ContractUtils.USER_TYPE_S.equals(user.getUserType())){
			queryFilter.addFilter("supplierId", user.getId().toString(), QueryOP.EQUAL);
		}else{
			queryFilter.addFilter("merchantsLeading", user.getId().toString(), QueryOP.EQUAL);
		}
		Page<Assinfo> page = null;
		if(assrecords.getNegAssbrands()!=null && !assrecords.getNegAssbrands().isEmpty()){
			NegAssbrands brand = assrecords.getNegAssbrands().get(0);
			if(StringUtil.isNotEmpty(brand.getBrandCname())){
				queryFilter.addFilter("brandCname",brand.getBrandCname(), QueryOP.EQUAL);
				model.addAttribute("brandCname", brand.getBrandCname());
				page = (Page<Assinfo>) assinfoService.find1(queryFilter);
			}else
				page = (Page<Assinfo>) assinfoService.find(queryFilter);	
		}else	
		page = (Page<Assinfo>) assinfoService.find(queryFilter);
		model.addAttribute("page", page);
		model.addAttribute("list", page.getList());
		model.addAttribute("assrecords", assrecords);
		return resultPage("/biz/contract/assrecord/list", model, request);
	}
	
	/**
	 * 查看意向洽谈
	 * @author LIUWEI
	 */
	@RequestMapping(value="get")
	public String get(Long id, HttpServletRequest request, Model model){
		String navId = request.getParameter("navId");
		Assrecords ass = assrecordService.get(id);			//根据id获得最新版本数据
		
		//根据招商编号获得相应招商分类名称
		if(ass.getNegAssbrands()!=null){			
			for(int i=0; i<ass.getNegAssbrands().size(); i++){
				try {
					String name = BuildEntity.getCateName(ass.getNegAssbrands().get(i).getInviteCate(), icmCateService);
					ass.getNegAssbrands().get(i).setInviteCateName(name);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		//根据扣率编码获得相应名称
		if(ass.getNegAssitems() != null){
			for(int i=0; i<ass.getNegAssitems().size(); i++){
				String deductCode = ass.getNegAssitems().get(i).getDeductCode();
				String taxRate = ass.getNegAssitems().get(i).getTaxRate();
				ass.getNegAssitems().get(i).setTaxRateName(BuildEntity.getTaxRateName(articleService, deductCode, taxRate, ass.getAssinfo().getStoreId()));
			}
		}
		
		if(UserUtils.getCurrentUserId().toString().equals(ass.getAssinfo().getSupplierLeading())){
			model.addAttribute("status", ContractUtils.NEG_STATUS_GYS);			//当前用户为供应商
		}else if(UserUtils.getCurrentUserId().toString().equals(ass.getAssinfo().getMerchantsLeading())){
			model.addAttribute("status", ContractUtils.NEG_STATUS_CGY);			//当前用户为采购人
		}
		
		model.addAttribute("assrecords", ass);
		model.addAttribute("assinfo", ass.getAssinfo());
		//根据合同类型控制跳转页面
		String resultPage = BuildEntity.getResultPage(ass.getAssinfo().getContractType(), "view");
		model.addAttribute("navId", navId);
		return "/biz/contract/assrecord/"+resultPage;
	}
	
	
	/**
	 * 修改意向洽谈(说明：每次修改洽谈都会生成一条新的记录)
	 * @author LIUWEI
	 */
	@RequestMapping(value="add")
	public String add(Long assinfoId, HttpServletRequest request, Model model){
		Assrecords assrecords = assrecordService.getByBaseinfoId(assinfoId);
		HashMap<Object, Object> idMap=(HashMap<Object, Object>) Maps.newHashMap();
		HashMap<Object, Object> idParMap =(HashMap<Object, Object>) Maps.newHashMap();
		BigDecimal training = new BigDecimal(200);
		BigDecimal jobCard = new BigDecimal(20);
		assrecords.setIsTrainingAmount(training);
		assrecords.setIsJobCardAmount(jobCard);
		if(assrecords != null){
			//变更复制功能处理
			if(assrecords.getNegAssbaseitems() != null){			//因为每次修改洽谈都是产生一条新的记录。。所以每次修改都需要重新产生行的id。 此步骤目的就是解决这个问题
				for(int i=0; i<assrecords.getNegAssbaseitems().size(); i++){
//					assrecords.getNegAssbaseitems().get(i).setId(idGenerator.getUId());
					NegAssbaseitems baseitems = assrecords.getNegAssbaseitems().get(i);
					idMap.put(baseitems.getId().toString(), idGenerator.getUId());			//原条款id作为key， 新产生的id作为value保存到map。 用于后面替换针对这条数据复制出来的条款的辅助id
					if(!StringUtils.isEmpty(baseitems.getAssistId())){
						idParMap.put(baseitems.getId().toString(),baseitems.getAssistId());	//原条款id做为key，辅助id作为value保存到map。
					}
				}	
				
				for(int i=0; i<assrecords.getNegAssbaseitems().size(); i++){
					NegAssbaseitems baseitems = assrecords.getNegAssbaseitems().get(i);
					if(idParMap.get(baseitems.getId().toString()) != null){				
						if(idParMap.get(baseitems.getId().toString()).equals(baseitems.getAssistId())){		//如果复制的条款的辅助id等于主条款的id。 那就把主条款新的id赋值给复制的条款辅助id 
							baseitems.setAssistId(String.valueOf(idMap.get(baseitems.getAssistId().toString())));	
						}
					}
					if(idMap.get(baseitems.getId().toString())!=null){
						baseitems.setId((Long)idMap.get(baseitems.getId().toString()));
					}
				}
			}
			
			//根据招商编号获得招商分类名称
			if(assrecords.getNegAssbrands()!=null){			
				for(int i=0; i<assrecords.getNegAssbrands().size(); i++){
					try {
						String name = BuildEntity.getCateName(assrecords.getNegAssbrands().get(i).getInviteCate(), icmCateService);
						assrecords.getNegAssbrands().get(i).setInviteCateName(name);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			
			//根据扣率编码获得相应名称
			if(assrecords.getNegAssitems() != null){
				for(int i=0; i<assrecords.getNegAssitems().size(); i++){
					String deductCode = assrecords.getNegAssitems().get(i).getDeductCode();
					String taxRate = assrecords.getNegAssitems().get(i).getTaxRate();
					assrecords.getNegAssitems().get(i).setTaxRateName(BuildEntity.getTaxRateName(articleService, deductCode, taxRate,assrecords.getAssinfo().getStoreId()));
				}
			}
			
			model.addAttribute("assinfo", assrecords.getAssinfo());
			model.addAttribute("assrecords", assrecords);
		}
		String navId = request.getParameter("navId");
		model.addAttribute("navId", navId);
		model.addAttribute("contractType", assrecords.getAssinfo().getContractType());		//合同类型  联营
		model.addAttribute("negType", assrecords.getAssinfo().getNegotiationType());	//洽谈类型	 新签
		String resultPath = BuildEntity.getResultPage(assrecords.getAssinfo().getContractType(), "add");
		return resultPage("/biz/contract/assrecord/"+resultPath, model, request);
	}

	
	/**
	 * 从合同处入口（如变更、续签、展期等）
	 * @param contractId		//合同号
	 * @param type				//洽谈类型
	 * @param isModifyContract	//是否变更合同
	 * @author liuwei
	 */
	@RequestMapping(value="editAssociated")
	public String edit(String contractId, String type, String contractType, String isModifyContract, Model model, HttpServletRequest request){
		Assrecords assrecords = null;
		String resultPath = "";		//返回的页面
		if(contractType.equals(ContractUtils.CONTRACT_TYPE_LY)){					//联营合同
			assrecords = editAssociated(contractId, isModifyContract);
		}else if(contractType.equals(ContractUtils.CONTRACT_TYPE_ZY_JX) || contractType.equals(ContractUtils.CONTRACT_TYPE_ZY_DX)){		//自营合同
			assrecords = editSelfAssociated(contractId, isModifyContract);
		}else if(contractType.equals(ContractUtils.CONTRACT_TYPE_CX)){				//促销合同
			assrecords = editMarketAssociated(contractId, isModifyContract);		
		}else if(contractType.equals(ContractUtils.CONTRACT_TYPE_ZP)){				//租赁专柜合同  
			assrecords = editLeaseAssociated(contractId, isModifyContract);			
		}else if(contractType.equals(ContractUtils.CONTRACT_TYPE_GG)){				//广告
			assrecords = editAdvertAssociated(contractId, isModifyContract);	
		}
		
		//根据招商编号获得相应招商分类名称
		if(assrecords.getNegAssbrands()!=null){			
			for(int i=0; i<assrecords.getNegAssbrands().size(); i++){
				try {
					String name = BuildEntity.getCateName(assrecords.getNegAssbrands().get(i).getInviteCate(), icmCateService);
					assrecords.getNegAssbrands().get(i).setInviteCateName(name);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
				
		//根据扣率编码获得相应名称
		if(assrecords.getNegAssitems() != null){
			for(int i=0; i<assrecords.getNegAssitems().size(); i++){
				String deductCode = assrecords.getNegAssitems().get(i).getDeductCode();
				String taxRate = assrecords.getNegAssitems().get(i).getTaxRate();
				assrecords.getNegAssitems().get(i).setTaxRateName(BuildEntity.getTaxRateName(articleService, deductCode, taxRate,assrecords.getAssinfo().getStoreId()));
			}
		}
				
		//如何合同属性为先申号，则把合同属性改为新签
		if(ContractUtils.CONTRATC_ATTRIBUTE_XSH.equals(type)){	
			type = ContractUtils.CONTRATC_ATTRIBUTE_XINQ;
		}
		resultPath = BuildEntity.getResultPage(contractType, "add");
		if(assrecords != null){
			model.addAttribute("assinfo", assrecords.getAssinfo());
			model.addAttribute("assrecords", assrecords);
		}
		model.addAttribute("contractType", contractType);		//合同类型  联营
		model.addAttribute("negType", type);		//洽谈类型
		
		//如果是展期， 系统自动给合同期限延期三个月
		if(ContractUtils.CONTRATC_ATTRIBUTE_ZQ.equals(type) && !ContractUtils.NEG_ISMODIFYCONTRACT_Y.equals(isModifyContract)){
			Date date = assrecords.getEndDate();
			Calendar rightNow = Calendar.getInstance();
		    rightNow.setTime(date);
		    rightNow.add(Calendar.MONTH,3);
		    assrecords.setStartDate(assrecords.getEndDate());
		    assrecords.setEndDate(rightNow.getTime());
		}
		//如果是续签， 系统自动给合同期限延期一年
		if(ContractUtils.CONTRATC_ATTRIBUTE_XUQ.equals(type) && !ContractUtils.NEG_ISMODIFYCONTRACT_Y.equals(isModifyContract)){
			Date date = assrecords.getEndDate();
			Calendar rightNow = Calendar.getInstance();
		    rightNow.setTime(date);
		    rightNow.add(Calendar.MONTH,12);
		    assrecords.setStartDate(assrecords.getEndDate());
		    assrecords.setEndDate(rightNow.getTime());
		}
		return resultPage("/biz/contract/assrecord/"+resultPath, model, request);
	}
	
	
	/**
	 * 创建新洽谈记录
	 * @author LIUWEI
	 * @throws Exception 
	 */
	@RequestMapping(value="save")
	public String save(Assrecords assrecords, String positionLog, RedirectAttributes redirectAttributes, HttpServletRequest request, Model model) throws Exception{
		String navId = request.getParameter("navId");
		assrecordService.save(assrecords); 	//保存洽谈记录
		
		String[] postitionId = positionLog.split(",");		//修改招商信息数据的状态
		for(int i=0; i<postitionId.length; i++){
			if(postitionId[i] != null && !postitionId[i].isEmpty()){
				Long id = Long.parseLong(postitionId[i]);
				BrandPositionLog log = new BrandPositionLog();
				log.setStatus(BrandCommonConstant.BRANDPOSITION_SATUES_20);
				log.setId(id);
				brandPositionLogService.update(log);
			}
		}
		sendMessage(assrecords.getAssinfo(), assrecords.getId(), navId);		//发送待办
		updIsApprove(assrecords.getAssinfo().getContractType(), assrecords.getAssinfo().getContractId(), ContractUtils.NEG_ISAPPROVE_Y);
		addMessage(redirectAttributes, "保存成功:"+assrecords.getAssinfo().getNumber());
		return "redirect:getList?navId="+navId;
	}
	
	
	
	public Message sendMessage(Assinfo assinfo, Long assrecordsID, String navId){
		//Assinfo assinfo = assinfoService.get(assinfoID);
		String psersonId = "";
		Long currentUserId = UserUtils.getCurrentUserId();
		if(currentUserId.toString().equals(assinfo.getSupplierLeading())){		//如果发起洽谈的人是供应商，则将待办发送给采购人
			psersonId = assinfo.getMerchantsLeading().toString();
		}else if(currentUserId.toString().equals(assinfo.getMerchantsLeading())){	//如果发起洽谈的人是采购人，则将待办发送给供应商
			psersonId = assinfo.getSupplierLeading();
		}
		TodoMessage message = new TodoMessage();
		List<String> personIds = Lists.newArrayList();
		personIds.add(psersonId);
		message.setTitle(UserUtils.getCurrentUserName()+"发来一份意向洽谈,请尽快处理。");
		message.setTitleLink("biz/contract/assrecord/get?id="+assrecordsID+"&navId="+navId);
		message.setContent("");
		message.setContentTypeFlag(MessageConstant.TODO_CONTENT_TYPE_TEXT);
		message.setCreateBy(UserUtils.getCurrentUserId().toString());
		message.setCreateDate(new Date());
		message.setPersonIds(personIds);
		message.setMessageType(MessageConstant.TODO_TYPE_NOTIFY);
		Message msg = null;
		try {
//			msg = mscServicec.send(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msg;
	}
	
	
	
	/**
	 * 	从招商入口发起的洽谈
	 */
	@RequestMapping(value="brandAdd")
	public String brandAdd(String strIds, String contractType, String mainContractNo, Model model, HttpServletRequest request){
		String[] ids = strIds.split(",");
		Long id = 0L;
		BrandPositionLog brandPosition = null;
		List<NegAssshops> shopList = new ArrayList<NegAssshops>();
		StringBuffer  brandNo =  new StringBuffer();
		Assrecords assrecords = new Assrecords();
		for(int i=0; i<ids.length; i++){
			if(ids[i] != null && !ids.equals("")){
				id = Long.parseLong(ids[i]);
			}
			//获得需要洽谈的招商信息数据
			brandPosition = brandPositionLogService.get(id);		
			
			 //根据招商发布信息的招商编号获得商铺号的详细信息
			NegAssshops negAssshops = new NegAssshops();							
			BerthMaindata berthMaindata = berthMaindataService.getByMechId(brandPosition.getBrandPos().getMerchant_id());	//根据招商编号获得铺位数据	
			if(berthMaindata != null){
				negAssshops.setShop(berthMaindata.getBerthId());		//铺位号
				negAssshops.setShopId(berthMaindata.getMechId());		//招商编号
				assrecords.setBuildArea(berthMaindata.getArea());
			}
			shopList.add(negAssshops);
			assrecords.setNegAssshopsList(shopList);
			
			brandNo.append(brandPosition.getBrandCate().getBrandNo()).append(",");
		}
		
		/**
		 * 由于是同一楼层、门店、供应商下，这里只需要填充一次即可
		 */
		Assinfo info = new Assinfo();
		info.setArea(brandPosition.getRegion().getName());					//区域名称
		info.setAreaId(brandPosition.getRegion().getCode());//区域ID
		info.setStore(brandPosition.getShop().getName());					//门店名称
		info.setStoreId(brandPosition.getShop().getNo());	//门店id
		info.setFloor(brandPosition.getBaseFloor().getName());				//楼层名称
		info.setFloorId(brandPosition.getBaseFloor().getCode());			//楼层id
		info.setShopId(brandPosition.getBrandPos().getMerchant_id());		//招商编号
		info.setShopId(brandNo.toString().substring(0, brandNo.length()-1));		//品牌编号
		info.setSupplierId(Long.parseLong(brandPosition.getSupplierId()));	//供应商id
		info.setSupplierName(brandPosition.getSupplier().getCname());		//供应商名称
		info.setSupplierNo(brandPosition.getSupplier().getSupplierNo());	//供应商编码
		info.setMainContractId(mainContractNo);	//主合同号
		
		//默认带出合同条款
		List<NegAssitems> negAssitemsList = new ArrayList<NegAssitems>();
		ContractArticleType contractArticleType = new ContractArticleType();
		contractArticleType.setArticle(contractType);
		List<ContractArticleType> contractArticleTypeList = contractArticleTypeService.getByContractType(contractArticleType);	//获得扣款项代码
		Calendar rightNow = Calendar.getInstance();
	    rightNow.setTime(new Date());
	    rightNow.add(Calendar.MONTH,3);
		for (ContractArticleType articleType : contractArticleTypeList) {
			//根据扣款项代码获得扣款项信息
			HashMap<String, String>  map  =new HashMap<String, String>();
			map.put("article", articleType.getContractType());
			map.put("shopId", info.getStoreId());
			ContractArticle article = contractArticleService.getContractRateCodeByNumber(map);	
			if(article != null){
				NegAssitems negAssitems = new NegAssitems();
				negAssitems.setDeductCode(article.getArticle());	//扣款项代码
				negAssitems.setDeductItem(article.getArticleName());//扣款项名称
				negAssitems.setAmount(BigDecimal.valueOf(0));		//金额
				negAssitems.setValidType("10");						//时效类型
				negAssitems.setDeductType("20");					//扣款方式
				negAssitems.setStartDate(new Date());				//开始日期
				negAssitems.setEndDate(rightNow.getTime());			//结束日期默认大于开始日期三个月
				
				ContractRateCode code = new ContractRateCode();
				code.setArticle(article.getArticle());
				code.setShopId(info.getStoreId());
				//根据扣款项代码获得扣率
				ContractRateCode contractRate = contractRateCodeService.getRateCode(code);	
				negAssitems.setTaxRate(contractRate.getRateCode());	//税率
				negAssitems.setCountBase(contractRate.getSalestype());//计算基数	
				negAssitems.setTaxRateName(BuildEntity.getTaxRateName(articleService, article.getArticle(), contractRate.getRateCode(), info.getStoreId()));
				negAssitemsList.add(negAssitems);
			}
		}
		
		//如果促销合同，则根据主合同号带出合同条款
		if(contractType.equals("Z600")){			
			negAssitemsList = getItemCodeByContractNo(mainContractNo);
			if(negAssitemsList != null){
				//只带出主合同的A类合同条款
				for(int i=0; i<negAssitemsList.size(); i++){
					String str = negAssitemsList.get(i).getDeductCode();
					if(!StringUtils.isEmpty(str)){
						if(!"A".equals(str.substring(0,1))){
							negAssitemsList.remove(i);
							i--;
							continue;
						}
					}
					//根据扣率编码获得相应名称
					String deductCode = negAssitemsList.get(i).getDeductCode();
					String taxRate = negAssitemsList.get(i).getTaxRate();
					negAssitemsList.get(i).setTaxRateName(BuildEntity.getTaxRateName(articleService, deductCode, taxRate,info.getStoreId()));
				}
			}
		}
		assrecords.setNegAssitems(negAssitemsList);
		
		//合同有效日期默认当前日期加三个月
		assrecords.setStartDate(new Date());			
		assrecords.setEndDate(rightNow.getTime());
		
		//如果自营合同，则根据自营合同类型默认对应的供应商经营方式。
		if(contractType.equals(ContractUtils.CONTRACT_TYPE_ZY_JX)){
			assrecords.setBusinessType(ContractUtils.BUSINESS_TYPE_RUNSELF_GX);
		}else if(contractType.equals(ContractUtils.CONTRACT_TYPE_ZY_DX)){
			assrecords.setBusinessType(ContractUtils.BUSINESS_TYPE_RUNSELF_DX);
		}
		
		model.addAttribute("assinfo", info);			
		model.addAttribute("assrecords", assrecords);		
		String navId = request.getParameter("navId");
		model.addAttribute("navId", navId);
		model.addAttribute("contractType", contractType);		//合同类型  联营
		model.addAttribute("negType", ContractUtils.CONTRATC_ATTRIBUTE_XINQ);	//洽谈类型	 新签
		model.addAttribute("positionLog", strIds);
		String resultPage = BuildEntity.getResultPage(contractType, "add");
		return "/biz/contract/assrecord/"+resultPage;
	}
	
	/**
	 * 显示洽谈结算条款页面
	 */
	@RequestMapping(value="showModalAssbaseitems")
	public String showModalAssbaseitems(String brandsId,String flag, String contractType, Model model){
		model.addAttribute("flag", flag);
		model.addAttribute("brandsId", brandsId);
		model.addAttribute("contractType", contractType);
		return "/biz/contract/assrecord/modalAssbaseitems";
	}
	
	/**
	 * 显示洽谈合同条款页面
	 * @author LIUWEI
	 */
	@RequestMapping(value="showModalAssitems")
	public String showModalAssitems(String deductCode, String flag, String contractType, Model model){
		model.addAttribute("deductCode", deductCode);
		model.addAttribute("flag", flag);
		model.addAttribute("contractType", contractType);
		return "/biz/contract/assrecord/modalAssitems";
	}
	
	/**
	 * 显示洽谈品牌页面
	 * @author LIUWEI
	 */
	@RequestMapping(value="showModalAssBrand")
	public String showModalAssBrand(String brandId, String supplierNo, String inviteCate, String flag, String brandNo, String iszs, Model model){
		CMCate cmcCate = null;
		String cateName = "";
		try {
			if(inviteCate!=null && !inviteCate.isEmpty() && !inviteCate.equals("undefined")){
				cmcCate = icmCateService.getByCateNo(inviteCate);
				cateName = cmcCate.getCateName();
				String cateNames = CommonContractController.getCateName(cmcCate, icmCateService);	//获得招商分类名称 
				cmcCate.setCateName(cateNames);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("operate","add");
		model.addAttribute("supplierNo", supplierNo);
		model.addAttribute("brandId", brandId);
		model.addAttribute("cateName", cateName);
		model.addAttribute("cmcCate", cmcCate);
		model.addAttribute("brandNo", brandNo);
		model.addAttribute("flag", flag);
		model.addAttribute("iszs", iszs);
		return "/biz/contract/assrecord/modalBrand";
	}
	

	/**
	 * 更新洽谈状态
	 * @author LIUWEI
	 */
	@RequestMapping(value="updateStatus")
	public String updateStatus(Long id, Long negId, int status, Model model, HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		String navId = request.getParameter("navId");
		map.put("id", id);
		map.put("status", status);
		assinfoService.updateStatus(map);
		
		Assinfo assinfo  = assinfoService.get(id);							
		sendMessage(assinfo, assinfo.getAssrecords().getId(), navId);		//发送待办
		if(ContractUtils.NEG_STATUS_ZZ.equals(status)){
			updIsApprove(assinfo.getContractType(), assinfo.getContractId(), ContractUtils.NEG_ISAPPROVE_N);
		}
		return "redirect:getList?navId="+navId;
	}
	
	/**
	 * 根据版本号查看洽谈数据
	 */
	@RequestMapping(value="{infoId}/getByVersion")
	public String getByVersion(@PathVariable Long infoId, int version, HttpServletRequest request, Model model){
		String navId = request.getParameter("navId");
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("infoId", infoId);
		map.put("version", version);
		Assrecords ass = assrecordService.getByVersion(map);
		
		if(UserUtils.getCurrentUserId().toString().equals(ass.getAssinfo().getSupplierLeading())){
			model.addAttribute("status", ContractUtils.NEG_STATUS_GYS);			//当前用户为供应商
		}else if(UserUtils.getCurrentUserId().toString().equals(ass.getAssinfo().getMerchantsLeading())){
			model.addAttribute("status", ContractUtils.NEG_STATUS_CGY);			//当前用户为采购人
		}
		model.addAttribute("assrecords", ass);
		model.addAttribute("assinfo", ass.getAssinfo());
		model.addAttribute("navId", navId);
		return "/biz/contract/assrecord/view";
	}
	
	/**
	 * 获得洽谈历史记录
	 */
	@RequestMapping(value="{infoId}/getVersionList")
	public String getVersionList(@PathVariable Long infoId, int version, HttpServletRequest request, Model model){
		String navId = request.getParameter("navId");
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("infoId", infoId);
		map.put("version", version);
		List<Assrecords> list = assrecordService.getPast(map);		//获得洽谈历史记录
		model.addAttribute("list", list);
		model.addAttribute("navId", navId);
		return "/biz/contract/assrecord/versionList";
	}
	
	@RequestMapping(value="{ids}/delete")
	public String delete(@PathVariable String ids, Model model, HttpServletRequest request){
		String navId = request.getParameter("navId");
		assrecordService.delete(ids);
		return "redirect:/biz/contract/assrecord/getList?navId="+navId; 
	}
	
	
	/**
	 * 改变合同是否洽谈的状态
	 * @param contractType	合同类型	
	 * @param contractId	合同ID
	 * @param isApprove		是否洽谈中
	 * @author liuwei
	 * @data 2014年6月24日
	 */
	public int updIsApprove(String contractType, Long contractId, String isApprove){
		int result = 0;
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("id", contractId);
		map.put("isApprove", isApprove);
		if(contractType.equals(ContractUtils.CONTRACT_TYPE_LY)){
			result =contractServce.updateIsApprove((HashMap) map);
		}else if(contractType.equals(ContractUtils.CONTRACT_TYPE_ZY_JX) || contractType.equals(ContractUtils.CONTRACT_TYPE_ZY_DX)){	//自营
			result=selfService.updateIsApprove((HashMap) map);
		}else if(contractType.equals(ContractUtils.CONTRACT_TYPE_CX)){			//促销
			result=marketService.updateIsApprove((HashMap) map);
		}else if(contractType.equals(ContractUtils.CONTRACT_TYPE_ZP)){			//租赁
			result=leaseService.updateIsApprove((HashMap)map);
		}else if(contractType.equals(ContractUtils.CONTRACT_TYPE_GG)){			//广告
			result = advertService.updIsApprove(map);
		}
		return result;
	}

	//*********************************构建合同对象***************************
	/**
	 * 构建联营洽谈对象
	 */
	public Assrecords editAssociated(String contractId, String isModifyContract){
		AssociatedContract associatedContract = contractServce.get(contractId);
		Assrecords assrecords = new Assrecords();
		if(associatedContract != null){			
			//洽谈记录
			assrecords = BuildEntity.buildAssrecords(associatedContract);
			//洽谈基本信息
			Assinfo assinfo = BuildEntity.buildAssinfo(associatedContract, isModifyContract);
			assrecords.setAssinfo(assinfo);
			//品牌数据
			List<NegAssbrands> assbrandsList = BuildEntity.buildAssBrand(associatedContract, icmCateService);
			assrecords.setNegAssbrands(assbrandsList);
			//销售分层及结算条款
			List<NegAssbaseitems> baseitemList = BuildEntity.buildBaseitems(associatedContract);
			assrecords.setNegAssbaseitems(baseitemList);
			//意向洽谈合同条款
			List<NegAssitems> itemsList = BuildEntity.buildAssitems(associatedContract);
			assrecords.setNegAssitems(itemsList);
			//临时扣款项费用
			List<NegAssTempItemCode> itemList = BuildEntity.buildTempitems(associatedContract);
			assrecords.setNegAssTempItemCodeList(itemList);
			//铺位数据
			List<NegAssshops> shopsList = BuildEntity.buildAssshops(associatedContract);
			assrecords.setNegAssshopsList(shopsList);
		}
		return assrecords;
	}
	
	/**
	 * 构建自营洽谈对象
	 */
	public Assrecords editSelfAssociated(String contractId, String isModifyContract){
		SelfAssociated associatedContract = selfService.get(contractId);
		Assrecords assrecords = new Assrecords();
		if(associatedContract != null){			
			//洽谈记录
			assrecords = BuildEntity.buildAssrecords(associatedContract);
			//洽谈基本信息
			Assinfo assinfo = BuildEntity.buildAssinfo(associatedContract, isModifyContract);
			assrecords.setAssinfo(assinfo);
			//品牌数据
			List<NegAssbrands> assbrandsList = BuildEntity.buildAssBrand(associatedContract);
			assrecords.setNegAssbrands(assbrandsList);
			//意向洽谈合同条款
			List<NegAssitems> itemsList = BuildEntity.buildAssitems(associatedContract);
			assrecords.setNegAssitems(itemsList);
			//临时扣款项费用
			List<NegAssTempItemCode> itemList = BuildEntity.buildTempitems(associatedContract);
			assrecords.setNegAssTempItemCodeList(itemList);
			//铺位数据
			List<NegAssshops> shopsList = BuildEntity.buildAssshops(associatedContract);
			assrecords.setNegAssshopsList(shopsList);
			//签约门店
			List<NegStore> storeList = BuildEntity.buildStore(associatedContract);
			assrecords.setStoreList(storeList);
		}
		return assrecords;
	}
	
	/**
	 * 促销自营洽谈对象
	 */
	public Assrecords editMarketAssociated(String contractId, String isModifyContract){
		MarketAssociated associatedContract = marketService.get(contractId);
		Assrecords assrecords = new Assrecords();
		if(associatedContract != null){			
			//洽谈记录
			assrecords = BuildEntity.buildAssrecords(associatedContract);
			//洽谈基本信息
			Assinfo assinfo = BuildEntity.buildAssinfo(associatedContract, isModifyContract);
			assrecords.setAssinfo(assinfo);
			//品牌数据
			List<NegAssbrands> assbrandsList = BuildEntity.buildAssBrand(associatedContract);
			assrecords.setNegAssbrands(assbrandsList);
			//销售分成及结算条款
			List<NegAssbaseitems> assbaseitems = BuildEntity.buildBaseitems(associatedContract);
			assrecords.setNegAssbaseitems(assbaseitems);
			//意向洽谈合同条款
			List<NegAssitems> itemsList = BuildEntity.buildAssitems(associatedContract);
			assrecords.setNegAssitems(itemsList);
			//临时扣款项费用
			List<NegAssTempItemCode> itemList = BuildEntity.buildTempitems(associatedContract);
			assrecords.setNegAssTempItemCodeList(itemList);
			//铺位数据
			List<NegAssshops> shopsList = BuildEntity.buildAssshops(associatedContract);
			assrecords.setNegAssshopsList(shopsList);
		}
		return assrecords;
	}
	
	/**
	 * 租赁自营洽谈对象
	 */
	public Assrecords editLeaseAssociated(String contractId, String isModifyContract){
		LeaseAssociated associatedContract = leaseService.get(contractId);
		Assrecords assrecords = new Assrecords();
		if(associatedContract != null){			
			//洽谈记录
			assrecords = BuildEntity.buildAssrecords(associatedContract);
			//洽谈基本信息
			Assinfo assinfo = BuildEntity.buildAssinfo(associatedContract, isModifyContract);
			assrecords.setAssinfo(assinfo);
			//品牌数据
			List<NegAssbrands> assbrandsList = BuildEntity.buildAssBrand(associatedContract);
			assrecords.setNegAssbrands(assbrandsList);
			//销售分成及结算条款
			List<NegAssbaseitems> assbaseitems = BuildEntity.buildBaseitems(associatedContract);
			assrecords.setNegAssbaseitems(assbaseitems);
			//意向洽谈合同条款
			List<NegAssitems> itemsList = BuildEntity.buildAssitems(associatedContract);
			assrecords.setNegAssitems(itemsList);
			//临时扣款项费用
			List<NegAssTempItemCode> itemList = BuildEntity.buildTempitems(associatedContract);
			assrecords.setNegAssTempItemCodeList(itemList);
			//铺位数据
			List<NegAssshops> shopsList = BuildEntity.buildAssshops(associatedContract);
			assrecords.setNegAssshopsList(shopsList);
		}
		return assrecords;
	}
	
	/**
	 * 广告自营洽谈对象
	 */
	public Assrecords editAdvertAssociated(String contractId, String isModifyContract){
		AdvertAssociated associatedContract = advertService.get(contractId);
		Assrecords assrecords = new Assrecords();
		if(associatedContract != null){			
			//洽谈记录
			assrecords = BuildEntity.buildAssrecords(associatedContract);
			//洽谈基本信息
			Assinfo assinfo = BuildEntity.buildAssinfo(associatedContract, isModifyContract);
			assrecords.setAssinfo(assinfo);
			//品牌数据
			List<NegAssbrands> assbrandsList = BuildEntity.buildAssBrand(associatedContract);
			assrecords.setNegAssbrands(assbrandsList);
			//意向洽谈合同条款
			List<NegAssitems> itemsList = BuildEntity.buildAssitems(associatedContract);
			assrecords.setNegAssitems(itemsList);
			//临时扣款项费用
			List<NegAssTempItemCode> itemList = BuildEntity.buildTempitems(associatedContract);
			assrecords.setNegAssTempItemCodeList(itemList);
			//铺位数据
			List<NegAssshops> shopsList = BuildEntity.buildAssshops(associatedContract);
			assrecords.setNegAssshopsList(shopsList);
		}
		return assrecords;
	}
	
	/**
	 * 根据主合同号获得临时条款项
	 * @author Liuwei
	 * @data 2014年8月15日
	 */
	public List<NegAssitems> getItemCodeByContractNo(String mainContractNo){
		List<NegAssitems> negAssitemsList = new ArrayList<NegAssitems>();
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("contractNo", mainContractNo);
		if(!StringUtils.isEmpty(mainContractNo)){
			int num = Integer.parseInt(mainContractNo.substring(0,1));
			switch (num) {
			case 1: 
				//联营合同
				List<AssociatedContract> associatedContractList = contractServce.getAssociatedWhere(map);	
				if(associatedContractList != null && associatedContractList.get(0).getAssitemsList() != null){
					negAssitemsList = BuildEntity.buildAssitems(associatedContractList.get(0));
				}
				break;
			case 2:
				//租赁合同
				List<LeaseAssociated> leaseAssociatedList = leaseAssContractService.getAssociatedWhere(map);
				if(leaseAssociatedList != null && leaseAssociatedList.get(0).getAssitemsList() != null){
					negAssitemsList = BuildEntity.buildAssitems(leaseAssociatedList.get(0));
				}
				break;
			case 3:
				//自营经销
				List<SelfAssociated> selfAssociated_dx = selfAssociatedService.getAssociatedWhere(map);
				if(selfAssociated_dx != null && selfAssociated_dx.get(0).getAssitemsList() != null){
					negAssitemsList = BuildEntity.buildAssitems(selfAssociated_dx.get(0));
				}
				break;
			case 4:
				//自营代销
				List<SelfAssociated> selfAssociated_jx = selfAssociatedService.getAssociatedWhere(map);
				if(selfAssociated_jx != null && selfAssociated_jx.get(0).getAssitemsList() != null){
					negAssitemsList = BuildEntity.buildAssitems(selfAssociated_jx.get(0));
				}
				break;
			case 5:
				//广告合同
				List<AdvertAssociated> advertAssociatedList = advertAssociatedService.getAssociatedWhere(map);
				if(advertAssociatedList != null && advertAssociatedList.get(0).getAssitemsList() != null){
					negAssitemsList = BuildEntity.buildAssitems(advertAssociatedList.get(0));
				}
				break;
			case 6:
				//促销合同
				List<MarketAssociated> marketAssociatedList = marketAssociatedService.getAssociatedWhere(map);
				if(marketAssociatedList != null && marketAssociatedList.get(0).getAssitemsList() != null){
					negAssitemsList = BuildEntity.buildAssitems(marketAssociatedList.get(0));
				}
				break;
			}
		}
		return negAssitemsList;
	}
}
